package com.github.xaidanwang.auth.server.util;

import com.github.xaidanwang.auth.server.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * Created by ace on 2017/9/10.
 */
public class JWTHelper {
    /**
     * 密钥加密token
     *
     * @param userInfo
     * @param singKey  秘钥
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(UserInfo userInfo, String signKey, int expire) throws Exception {
        Date expirationDate = new Date(System.currentTimeMillis() + expire * 1000);
        String compactJws = Jwts.builder()
                .setSubject(userInfo.getUsername())
                .claim("userId", userInfo.getUserid())
                .claim("nickname", userInfo.getNickname())
                .claim("userName", userInfo.getUsername())
                .claim("phone", userInfo.getPhone())
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .compact();
        return compactJws;
    }
    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String singKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(singKey).parseClaimsJws(token);
        return claimsJws;
    }
    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param singKey
     * @return
     * @throws Exception
     */
    public static UserInfo getInfoFromToken(String token, String singKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, singKey);
        Claims body = claimsJws.getBody();
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(body.getSubject());
        userInfo.setUserid(StringHelper.getObjectValue(body.get("userId")));
        userInfo.setPhone(Long.valueOf(StringHelper.getObjectValue(body.get("phone"))));
        userInfo.setNickname(StringHelper.getObjectValue(body.get("nickname")));
        return userInfo;
    }
}
